// pages/couponsEdit/couponsEdit.js
const util = require('../../utils/util')
import * as API_Coupons from '../../api/coupons'
import * as API_Config from '../../api/sysConfig'
Page({
 
  /**
   * 页面的初始数据
   */
  data: {
    title: '新建商家抵用券',
    listPage:null,
    selectClassifyList:[],
    showClassifyList:false,
    selectProductList:[],
    showProductList:false,
    fixedTimeStateIndex:'1',
    showFixedTimeState:false,
     // 提交状态
     showCommit:true,
    useStartTime:util.getDate(),
    useEndTime:util.getDate(),
    hotStateIndex:1,
    newUserIndex:1,
    appoinUnitIndex:0,
    YNArray: [
      {
        key: 'Y',
        value: '是'
      },
      {
        key: 'N',
        value: '否'
      }
    ],
    unitArray: [
      {
        value: '小时'
      },
      {
        value: '天'
      }
    ],
    coupons:{
      couponName:'',//名称
      money:0.0,//优惠券金额
      minPrice:0.0,//满多少可用
      limitedState:'N',//是否限量
      belongType:'store',
      newUserState:'N',//是否新人券
      couponType:'',//优惠券类型
      primaryKey:'',//关联主键
      receiveStartTime:'',//可领取开始时间
      receiveEndTime:'',//可领取结束时间
      fixedTimeState:'N',//是否固定有效期
      useStartTime:util.getDate(),//可使用开始时间
      useEndTime:util.getDate(),//可使用结束时间
      validDay:'',//有效期天数
      sort:'',//排序
      state:''//启用状态
    },
    couponTypeIndex:0,
    couponType:[],
    disabled: false,
    editFlag: false, //启用优惠券编辑
    couponId: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    API_Config.getDictData('jy_coupon_type').then(res=>{
      this.setData({
        couponType:res,
        'coupons.couponType':res[0].dictValue
      })
      if(res[0].dictValue == 'product'){
        this.setData({
          showProductList:true
        })
      }
      if(res[0].dictValue == 'classify'){
        this.setData({
          showClassifyList:true
        })
      }
    })

    if(options.id) {
      const that = this
      API_Coupons.getQuanDetail(options.id).then(res => {
        that.setData({
          couponId: options.id,
          title: '启用商家抵用券',
          editFlag: true,
          disabled: true,
          'coupons.couponName': res.coupons.couponName,
          'coupons.money': res.coupons.money,
          'coupons.minPrice': res.coupons.minPrice,
          newUserIndex: res.coupons.newUserState == 'N' ? 1 : 0,
          useStartTime: res.coupons.useStartTime,
          useEndTime: res.coupons.useEndTime,
          fixedTimeStateIndex: res.coupons.fixedTimeState == 'N' ? 1 : 0
        })
        if(res.classifyNameList.length > 0) {
          const arr = []
          res.classifyNameList.forEach(item => {
            arr.push({
              classifyName: item
            })
            that.setData({
              selectClassifyList: arr
            })
          })
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  changeCouponName(e){
    this.setData({
      'coupons.couponName':e.detail.value
    })
  },
  changePrice(e){
    this.setData({
      'coupons.money':e.detail.value
    })
  },
  changeMinPrice(e){
    this.setData({
      'coupons.minPrice':e.detail.value
    })
  },
  changeTotal(e){
    this.setData({
      'coupons.total':e.detail.value
    })
  },
  newUserPicker(e){
    let item = this.data.YNArray[e.detail.value]
    this.setData({
      'coupons.newUserState':item.key,
      newUserIndex:e.detail.value
    })
  },
  couponTypePicker(e){
    let item = this.data.couponType[e.detail.value]
    this.setData({
      'coupons.couponType':item.dictValue,
      couponTypeIndex:e.detail.value
    })
    if(item.dictValue == 'product'){
      this.setData({
        showProductList:true,
      })
    }else{
      this.setData({
        showProductList:false,
        selectProductList:[]
      })
    }
    if(item.dictValue == 'classify'){
      this.setData({
        showClassifyList:true,
      })
    }else{
      this.setData({
        showClassifyList:false,
        selectClassifyList:[]
      })
    }
  },
  fixedTimeStateIndexChange(e){
    let item = this.data.YNArray[e.detail.value]
    this.setData({
      'coupons.fixedTimeState':item.key,
      fixedTimeStateIndex:e.detail.value
    })
    if(item.key == 'Y'){
      this.setData({
        showFixedTimeState:true
      })
    }else{
      this.setData({
        showFixedTimeState:false
      })
    }
  },
  changeValueDay(e){
    this.setData({
      'coupons.validDay':e.detail.value
    })
  },
  useStartTimeChange(e){
    this.setData({
      'coupons.useStartTime':e.detail.value,
      useStartTime:e.detail.value
    })
  },
  useEndTimeChange(e){
    this.setData({
      'coupons.useEndTime':e.detail.value,
      useEndTime:e.detail.value
    })
  },
  selectProduct(){
    wx.navigateTo({
      url: '/pages/couponsEditSelect/couponsEditSelect',
    })
  },
  selectClassify(){
    if(this.data.disabled) {
      return
    }
    wx.navigateTo({
      url: '/pages/couponsEditClassify/couponsEditSelectClassify',
    })
  },
  delItem(e){
    let arr = this.data.selectProductList
    arr.splice(e.currentTarget.dataset.index,1)
    this.setData({
      selectProductList:arr
    })
  },
  delClassify(e){
    if(this.data.editFlag) {
      return
    }
    let arr = this.data.selectClassifyList
    arr.splice(e.currentTarget.dataset.index,1)
    this.setData({
      selectClassifyList:arr
    })
  },
  saveAtt(e){
    let that = this
    if(this.data.editFlag) {
      const data = {
        id: this.data.couponId,
        useStartTime: this.data.useStartTime,
        useEndTime: this.data.useEndTime
      }
      API_Coupons.editCoupons(data).then(res => {
        API_Coupons.up(this.data.couponId).then(upRes => {
          wx.navigateTo({
            url: '/pages/couponsList/couponsList',
          })
        })
      })
      return
    }
    this.setData({showCommit:false})
    let coupons = this.data.coupons
    if(!coupons.couponName.trim()){
      wx.showToast({
        title: '请填写优惠券名称',
        icon:'none'
      })
      this.setData({showCommit:true})
      return
    }else if(coupons.money<=0){
      wx.showToast({
        title: '请填写优惠金额',
        icon:'none'
      })
      this.setData({showCommit:true})
      return
    }else if(coupons.minPrice<=0){
      wx.showToast({
        title: '请填写使用门槛',
        icon:'none'
      })
      this.setData({showCommit:true})
      return
    }else if(coupons.couponType == 'product'){
      if(this.data.selectProductList.length == 0){
        wx.showToast({
          title: '请选择适用商品',
          icon:'none'
        })
        this.setData({showCommit:true})
        return
      }
    }else if(coupons.couponType == 'classify'){
      if(this.data.selectClassifyList.length == 0){
        wx.showToast({
          title: '请选择适用品类',
          icon:'none'
        })
        this.setData({showCommit:true})
        return
      }
    }else if(coupons.fixedTimeState == 'Y'){
      coupons.validDay = coupons.validDay + ''
      if(!coupons.validDay.trim()){
        wx.showToast({
          title: '请填写有效期天数',
          icon:'none'
        })
        this.setData({showCommit:true})
        return
      }
    }
    let productIds = this.getIds(this.data.selectProductList)
    let classifyIds = this.getIds(this.data.selectClassifyList)
    if(!coupons.couponType == 'general'){}
      coupons.primaryKey = classifyIds.length > 0 ? classifyIds:productIds
      coupons.primaryKey = this.reFormatter(coupons.primaryKey)
    this.setData({showCommit:true})
    if(coupons.fixedTimeState == 'Y'){
      coupons.useEndTime = ''
      coupons.useStartTime = ''
    }
    API_Coupons.create(coupons).then(res=>{
      if(res.id){
        wx.showToast({
          title: '添加成功',
        })
        var pages = getCurrentPages();
        var prevPage = pages[pages.length - 2];
        if (prevPage) {
          prevPage.flush()
          wx.navigateBack({
            //返回上一级
            delta: 1,
          })
        }
      }
    })
  },
  getIds(e){
    let ids = []
    for(let item of e){
      ids.push(item.id)
    }
    return ids
  },
  reFormatter(e){
    var str = ''
    var ids = e.join(",")
    str = ","+ids+","
    return str
  }
})